﻿using DeviceAlarmService.SystemService;
using System.IO.Ports;
using System.Text;
using System.Text.Json;

namespace DeviceAlarmService.MessagePush.Communication
{
    public class SerialPortCommunication : ICommunication
    {
        private object Lock = new();
        private SerialPort fSerialPort;

        public bool IsConnected { get { return fSerialPort.IsOpen; } }

        public void SendSMS(string phone, string message, out string results)
        {
            lock (Lock)
            {
                if (fSerialPort.IsOpen)
                {
                    string str_Content = phone + ":0:" + message;
                    fSerialPort.Write(str_Content);
                }

                results = "";
            }
        }

        public void SendCall(string phone, string message, out string results)
        {
            lock (Lock)
            {
                if (fSerialPort.IsOpen)
                {
                    string str_Content = phone + ":3:" + message;
                    fSerialPort.Write(str_Content);

                }
                results = "";
            }
        }

        public bool Connect()
        {
            try
            {
                Models.Message.SerialCommunication serialCommunication = JsonSerializer.Deserialize<Models.Message.SerialCommunication>(ConfigService.Configuration.passagewayMessage);
                if (!fSerialPort.IsOpen)
                {
                    fSerialPort.BaudRate = serialCommunication.baudRate;              //设置波特率
                    fSerialPort.PortName = serialCommunication.serialPort;     //设置COM端口
                    fSerialPort.Encoding = Encoding.GetEncoding("GBK");
                    fSerialPort.Open();                       //串行端口开启                    
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        public void Disconnect()
        {
            try
            {
                if (fSerialPort.IsOpen)
                {
                    fSerialPort.Close();
                }
            }
            catch
            {

            }
        }
    }
}
